package top.korori.common.exception;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import top.korori.common.model.Result;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

import static top.korori.common.enums.StatusCode.SYSTEM_ERROR;
import static top.korori.common.enums.StatusCode.VALID_ERROR;

/**
 * 全局异常处理
 *
 **/
@Slf4j
@RestControllerAdvice
public class ControllerAdviceHandler {

    /**
     * 处理服务异常
     *
     * @param e 异常
     * @return 接口异常信息
     */
    @ExceptionHandler(BizException.class)
    public Result<?> errorHandler(BizException e, HttpServletRequest request) {
        String requestURI = request.getRequestURI();
        log.info("业务异常:{},错误代码:{},请求路径:{},",e.getMsg(),e.getCode(),requestURI);
        return Result.fail(e.getCode(), e.getMsg());
    }


    /**
     * 拦截未知的运行时异常
     */
    @ExceptionHandler(RuntimeException.class)
    public Result<?> handleRuntimeException(RuntimeException e, HttpServletRequest request)
    {
        String requestURI = request.getRequestURI();
        log.error("请求地址'{}',发生未知异常.", requestURI, e);
        return Result.fail(SYSTEM_ERROR);
    }


    /**
     * 请求方式不支持
     */
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public Result<?> handleHttpRequestMethodNotSupported(HttpRequestMethodNotSupportedException e,
                                                          HttpServletRequest request)
    {
        String requestURI = request.getRequestURI();
        log.error("请求地址'{}',不支持'{}'请求", requestURI, e.getMethod());
        return Result.fail(e.getMessage());
    }

    /**
     * 处理参数校验异常
     *
     * @param e 异常
     * @return 接口异常信息
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result<?> errorHandler(MethodArgumentNotValidException e) {
        log.debug(e.getMessage());
        return Result.fail(VALID_ERROR.getCode(), Objects.requireNonNull(e.getBindingResult().getFieldError()).getDefaultMessage());
    }

    /**
     * 处理系统异常
     *
     * @param e 异常
     * @return 接口异常信息
     */
    @ExceptionHandler(Exception.class)
    public Result<?> errorHandler(Exception e) {
        log.error(e.getMessage(),e);
        return Result.fail(SYSTEM_ERROR.getCode(),"服务器运行异常");
    }

}
